<template>
	<view>
		
		<view class="container">
			<uni-search-bar radius="100" placeholder="搜索歌曲或歌手" v-model="searchKeyword" @confirm="search"
				@input="handleInput" cancelButton="none"></uni-search-bar>
		</view>
		<!-- 历史记录 -->
		<view v-if="showHistory" class="history-section">
			<view class="history-header">
				<text class="history-title">搜索历史</text>
				<text class="clear-btn" @tap="clearHistory">清空</text>
			</view>
			<view class="history-tags">
				<view v-for="(item, index) in historyList" :key="index" class="history-tag" @tap="selectHistory(item)">
					<text>{{ item }}</text>
					<text class="close" @tap.stop="removeHistory(index)">×</text>
				</view>
			</view>
		</view>
		<!-- 热门搜索 -->
		<view v-if="showHot && !searchKeyword" class="hot-search">
			<text class="hot-title">热搜榜</text>
			<view class="hot-list">
				<view v-for="(item, index) in hotList" :key="index" class="hot-item" @tap="selectHot(item.searchWord)">
					<view class="left">
						<text class="index" :class="{ 'top3': index < 3 }">{{ index + 1 }}</text>
						<view class="info">
							<view class="search-word">
								{{ item.searchWord }}
								<text v-if="item.iconUrl" class="tag">
									<image :src="item.iconUrl" class="tag-icon" mode="widthFix" />
								</text>
							</view>
							<text class="content" v-if="item.content">{{ item.content }}</text>
						</view>
					</view>
					<text class="score">{{ formatScore(item.score) }}</text>
				</view>
			</view>
		</view>
		<!-- 搜索建议 -->
		<scroll-view v-else-if="suggestList.length > 0 && !songs.length" class="suggest-list" scroll-y>
			<view v-for="(item, index) in suggestList" :key="index" class="suggest-item"
				@tap="selectSuggest(item.keyword)">
				<text class="keyword">{{ item.keyword }}</text>
				<text class="type" v-if="item.type">- {{ typeMap[item.type] }}</text>
			</view>
		</scroll-view>
		<!-- 搜索结果 -->
		<view v-if="songs.length > 0" class="result-list">
			<view class="search-header">
				<text class="search-keyword">"{{ searchKeyword }}"</text>
				<text class="search-count">找到{{ songs.length }}首歌曲</text>
			</view>
			<view class="song-list">
				<view v-for="(item, index) in songs" :key="index" class="song-item" @tap="playSong(item)">
					<view class="song-info">
						<text class="song-name">{{ item.name }}</text>
						<view class="song-source">
							<text class="source-text">{{ getSongSource(item) }}</text>
						</view>
					</view>
					<text class="play-icon" @tap="playSong(item)"><span class="iconfont icon-bofang"></span></text>
				</view>
			</view>
		</view>
		<!-- 空状态 -->
		<view v-if="showEmpty" class="empty">
			<text>暂无相关结果</text>
		</view>
	</view>
</template>

<script>
	import {
		getSearchHotDetail,
		getSearchSuggest,
		searchWord
	} from '../../common/api.js';

	export default {
		data() {
			return {
				searchKeyword: '',
				historyList: [], // 历史记录
				hotList: [], // 热门搜索
				suggestList: [], // 搜索建议
				songs: [], // 搜索结果
				showHot: true, // 显示热门
				typeMap: { // 类型映射
					1: '单曲',
					10: '专辑',
					100: '歌手'
				}
			}
		},
		computed: {
			showEmpty() {
				return this.searchKeyword && !this.songs.length && !this.suggestList.length
			},
			showHistory() {
				return this.historyList.length > 0 && !this.searchKeyword
			}
		},
		async created() {
			await this.loadHotSearch()
			this.loadHistory()
		},
		methods: {
			// 历史记录相关方法
			loadHistory() {
				const history = uni.getStorageSync('searchHistory') || []
				this.historyList = history.slice(0, 10) // 最多显示10条
			},
			saveHistory(keyword) {
				keyword = keyword.trim()
				if (!keyword) return

				// 去重处理
				const index = this.historyList.indexOf(keyword)
				if (index > -1) {
					this.historyList.splice(index, 1)
				}

				// 添加到开头并限制数量
				this.historyList.unshift(keyword)
				if (this.historyList.length > 10) {
					this.historyList.pop()
				}

				uni.setStorageSync('searchHistory', this.historyList)
			},

			clearHistory() {
				uni.removeStorageSync('searchHistory')
				this.historyList = []
			},

			removeHistory(index) {
				this.historyList.splice(index, 1)
				uni.setStorageSync('searchHistory', this.historyList)
			},

			selectHistory(keyword) {
				this.searchKeyword = keyword
				this.search()
			},

			// 加载热门搜索
			async loadHotSearch() {
				try {
					const res = await getSearchHotDetail()
					this.hotList = res.data.map(item => ({
						searchWord: item.searchWord,
						score: item.score,
						content: item.content,
						iconUrl: item.iconUrl
					}))
				} catch (e) {
					console.error('获取热门搜索失败:', e)
				}
			},

			// 热度值格式化
			formatScore(score) {
				if (score > 10000) {
					return (score / 10000).toFixed(1) + '万'
				}
				return score
			},

			// 输入处理
			async handleInput() {
				if (!this.searchKeyword.trim()) {
					this.suggestList = []
					this.songs = []
					this.showHot = true
					return
				}
				try {
					const res = await getSearchSuggest(this.searchKeyword)
					// 适配网易云实际返回结构
					if (res.data.result) {
						this.suggestList = res.data.result.allMatch || []
						if (this.suggestList.length === 0 && res.data.result.songs) {
							this.suggestList = res.data.result.songs.map(song => ({
								keyword: song.name,
								type: 1
							}))
						}
					}
					this.showHot = false
				} catch (e) {
					console.error('搜索建议获取失败:', e)
				}
			},

			// 执行搜索
			async search() {
				if (!this.searchKeyword.trim()) return

				// 保存搜索历史
				this.saveHistory(this.searchKeyword)

				try {
					// 使用搜索接口获取完整结果
					const res = await searchWord(this.searchKeyword)
					if (res[1].data.code === 200) {
						this.songs = res[1].data.result.songs || []
					} else {
						this.songs = []
					}
					this.suggestList = []
				} catch (e) {
					console.error('搜索失败:', e)
					this.songs = []
				}
			},

			// 选择热门搜索
			selectHot(keyword) {
				this.searchKeyword = keyword
				this.search()
			},

			// 选择搜索建议
			selectSuggest(keyword) {
				this.searchKeyword = keyword
				this.search()
			},

			// 获取歌曲来源信息
			getSongSource(item) {
				if (item.artists && item.album) {
					return `${item.artists[0].name} - ${item.album.name}`
				}
				return item.ar ? `${item.ar[0].name} - ${item.al.name}` : '未知来源'
			},

			// 播放歌曲
			playSong(song) {
				uni.navigateTo({
					url: `/pages/player/player?id=${song.id}`
				})
			}
		}
	}
</script>

<style>
	.container {
		padding: 20rpx;
	}

	/* 历史记录样式 - 修改为图片样式 */
	.history-section {
		padding: 30rpx;
	}

	.history-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.history-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.clear-btn {
		font-size: 28rpx;
		color: #888;
	}

	.history-tags {
		display: flex;
		flex-wrap: wrap;
	}

	.history-tag {
		position: relative;
		background: #f8f8f8;
		border-radius: 8rpx;
		padding: 15rpx 40rpx 15rpx 20rpx;
		margin: 0 20rpx 20rpx 0;
		font-size: 28rpx;
		color: #333;
	}

	.history-tag .close {
		position: absolute;
		right: 10rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #bbb;
		font-size: 36rpx;
		line-height: 1;
	}

	/* 热门搜索 */
	.hot-search {
		padding: 0 30rpx;
	}

	.hot-title {
		display: block;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		padding: 30rpx 0;
	}

	.hot-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.left {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.index {
		width: 40rpx;
		text-align: center;
		font-size: 34rpx;
		color: #999;
		margin-right: 30rpx;
	}

	.top3 {
		color: #fa3d3d;
	}

	.info {
		flex: 1;
	}

	.search-word {
		font-size: 30rpx;
		color: #333;
		display: flex;
		align-items: center;
	}

	.tag {
		margin-left: 15rpx;
	}

	.tag-icon {
		width: 60rpx;
		height: 30rpx;
	}

	.content {
		display: block;
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.score {
		font-size: 24rpx;
		color: #999;
	}

	/* 搜索建议 */
	.suggest-list {
		max-height: 60vh;
		padding: 0 30rpx;
	}

	.suggest-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.keyword {
		font-size: 30rpx;
		color: #333;
	}

	.type {
		font-size: 24rpx;
		color: #888;
		margin-left: 20rpx;
	}

	/* 搜索结果 */
	.result-list {
		padding: 0 30rpx;
		max-height: 70vh;
		overflow-y: auto;
	}

	.search-header {
		padding: 30rpx 0 20rpx;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 20rpx;
	}

	.search-keyword {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.search-count {
		font-size: 26rpx;
		color: #888;
		margin-left: 20rpx;
	}


	.song-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.play-icon {
		color: #888;
		font-size: 36rpx;
		padding: 0 20rpx;
	}

	.song-info {
		flex: 1;
		overflow: hidden;
	}

	.song-name {
		display: block;
		font-size: 32rpx;
		color: #333;
		line-height: 1.4;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.song-source {
		display: flex;
		align-items: center;
		margin-top: 10rpx;
	}

	.source-text {
		font-size: 26rpx;
		color: #888;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/* 空状态 */
	.empty {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
	}
</style>